package cn.liccshop.sys.zhifubao;

import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.exception.MySystemException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 支付宝支付页面
 * @since 2019-05-29-00:04
 */
@Component
public class MyPay {
    /**
     * 支付接口
     * 需要订单号 和价钱
     * @param orderSn
     * @param price
     * @return
     * @throws MySystemException
     */
    public String pay(String orderSn, String price) throws MySystemException {
        String payUrl = "";
        AlipayClient alipayClient = new DefaultAlipayClient(Constants.ZHI_FU_BAO_GATEWAY_URL, Constants.ZHI_FU_BAO_APP_ID, Constants.ZHI_FU_BAO_PRIVATE_KEY, "json", "utf-8", Constants.ZHI_FU_BAO_APP_PUBILC_KEY, "RSA2");
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(Constants.ZHI_FU_BAO_PAY_RETURN_URL);
        alipayRequest.setNotifyUrl("http://120.79.56.38/alipay.trade.page.pay-JAVA-UTF-8/notify_url.jsp");
        /** 订单编号 **/
        String out_trade_no = orderSn;
        /** 金额 **/
        String total_amount = price;
        /** 名称 **/
        String subject = Constants.APP_NAME;
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + subject + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        try {
            System.out.println(alipayClient.pageExecute(alipayRequest));
            String url = alipayClient.pageExecute(alipayRequest).getBody();
            payUrl = url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MySystemException("调用支付宝服务不可用", Constants.SERVICE_FAIL);
        }
        return payUrl;
    }

    /**
     * 验证是否支付
     * 支付成功-true；支付失败-false;
     * @param orderSn
     * @return
     */
    public Map<String, Object> verificationPay(String orderSn) {
        String trade_no ="";
        String queryResult = "";
        Map<String, Object> data = new HashMap<>();
        AlipayClient alipayClient = new DefaultAlipayClient(Constants.ZHI_FU_BAO_GATEWAY_URL, Constants.ZHI_FU_BAO_APP_ID, Constants.ZHI_FU_BAO_PRIVATE_KEY, "json", "utf-8", Constants.ZHI_FU_BAO_PUBILC_KEY, "RSA2");
        AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest();
        alipayTradeQueryRequest.setBizContent("{\"out_trade_no\":\"" + orderSn + "\"," + "\"trade_no\":\"" + trade_no + "\"}");
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(alipayTradeQueryRequest);
            queryResult = response.getTradeStatus();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("TRADE_SUCCESS".equals(queryResult)) {
            data.put("succ", true);
            data.put("payTime", response.getSendPayDate());
            return data;
        } else {
            data.put("succ", false);
            return data;
        }
    }
    /**
     * 退款
     * 退款成功 code: 1
     * 退款失败 code: 1127；message:###
     * @param orderSn
     * @return
     */
    public Map<String, Object> refund(String orderSn, String amount) throws MySystemException {
        Map<String, Object> result = new HashMap<>();
        String out_request_no ="";
        JSONObject queryResult = null;
        AlipayClient alipayClient = new DefaultAlipayClient(Constants.ZHI_FU_BAO_GATEWAY_URL, Constants.ZHI_FU_BAO_APP_ID, Constants.ZHI_FU_BAO_PRIVATE_KEY, "json", "utf-8", Constants.ZHI_FU_BAO_PUBILC_KEY, "RSA2");
        AlipayTradeRefundRequest alipayTradeQueryRequest = new AlipayTradeRefundRequest();
        alipayTradeQueryRequest.setBizContent("{\"out_trade_no\":\""+ orderSn +"\"," + "\"refund_amount\":\""+ amount +"\"," + "\"out_request_no\":\""+ out_request_no +"\"}");
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(alipayTradeQueryRequest);
            queryResult = JSON.parseObject(response.getBody()).getJSONObject("alipay_trade_refund_response");
        } catch (Exception e) {
            e.printStackTrace();
            throw new MySystemException("支付宝服务不可用，请稍后再试", Constants.SERVICE_FAIL);
        }
        if (queryResult.getString("msg").equals("Success")) {
            result.put("code", Constants.OK);
            result.put("message", "退款成功");
        } else {
            result.put("code", Constants.SERVICE_FAIL);
            result.put("message", "支付宝服务不可用，请稍后再试");
        }
        return result;
    }
}
